package com.ruoyi.ysg.aspect;

import com.ruoyi.ysg.annotation.AddTeacherId;
import com.ruoyi.ysg.utils.YsgUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * AOP切面，用于处理@AddTeacherId注解，自动添加teacherId参数
 */
@Aspect
@Component
public class TeacherIdAspect {

    /**
     * 拦截使用了@AddTeacherId注解的方法
     */
    @Before("@annotation(com.ruoyi.ysg.annotation.AddTeacherId)")
    public void addTeacherId(JoinPoint joinPoint) throws Throwable {
        // 获取目标方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取注解
        AddTeacherId annotation = method.getAnnotation(AddTeacherId.class);
        if (annotation == null) {
            return;
        }

        // 获取方法参数
        Object[] args = joinPoint.getArgs();

        // 获取teacherId
        Long teacherId = YsgUtils.getTeacherId();
        if (teacherId == null) {
            return;
        }

        // 遍历参数，找到需要添加teacherId的参数对象
        for (Object arg : args) {
            if (arg != null && !(arg instanceof String) && !(arg instanceof Number) && !(arg instanceof Boolean)) {
                // 尝试给参数对象添加teacherId字段
                try {
                    Field field = arg.getClass().getSuperclass().getDeclaredField("teacherIdQuery");
                    field.setAccessible(true);
                    field.set(arg, teacherId);
                } catch (NoSuchFieldException e) {
                    // 如果参数对象没有对应字段，继续检查下一个参数
                    continue;
                }
            }
        }
    }
}
